<template>
  <div>
    <el-dialog :visible.sync="showDialog" @open="onOpen" @close="close()"
               :title="dialogTitle">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <!-- 用户头像 -->
            <el-form-item label="用户头像">

              <!-- 头衔缩略图 -->
              <pan-thumb :image="this.formData.avatar"/>
              <!-- 文件上传按钮 -->
              <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
              </el-button>

              <!--
                v-show：是否显示上传组件
                :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                :url：后台上传的url地址
                @close：关闭上传组件
                @crop-upload-success：上传成功后的回调 -->
              <image-cropper
                  v-show="imagecropperShow"
                  :width="200"
                  :height="200"
                  :key="imagecropperKey"
                  :url="'/oss/uploadFile'"
                  field="file"
                  @close="closeImage"
                  @crop-upload-success="cropSuccess"/>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="departmentId">
              <el-select v-model="formData.departmentId" placeholder="请输入部门" clearable :style="{width: '100%'}">
                <el-option
                    v-for="item in departments"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="formData.nickname" placeholder="请输入昵称" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex" size="medium">
                <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入密码" clearable show-password
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机" prop="phoneNumber">
              <el-input v-model="formData.phoneNumber" placeholder="请输入手机" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birth">
              <el-date-picker v-model="formData.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                              :style="{width: '100%'}" placeholder="请选择生日" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import ImageCropper from '../../../../components/ImageCropper/index'
import PanThumb from '../../../../components/PanThumb/index'
import {addUser, deleteFile, editUser} from "@/network/system/user";
import {findDeptAndCount} from "@/network/system/dept";

export default {
  // 控制弹出框显示隐藏
  components: {
    ImageCropper,
    PanThumb
  },
  props: {
    addOrUpdateVisible: {
      type: Boolean,
      default: false
    },
    dialogTitle:{
      type:String,
      default: ''
    },
    userInfo:{
      type:Object,
      default:() => {
        return {}
      }
    }
  },
  data() {

    return {
      showDialog: false,//控制弹出框显示隐藏
      imagecropperShow: false, // 是否显示上传组件
      imagecropperKey: 0, // 上传组件id
      departments: [],
      formData: {
        username: undefined,
        avatar:'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
        departmentId: undefined,
        nickname: undefined,
        sex: undefined,
        password: undefined,
        email: undefined,
        phoneNumber: undefined,
        birth: null,
      },
      rules: {
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        departmentId: [{
          required: true,
          message: '请输入部门',
          trigger: 'change'
        }],
        nickname: [{
          required: true,
          message: '请输入昵称',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '性别不能为空',
          trigger: 'change'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '请输入邮箱',
          trigger: 'blur'
        }],
        phoneNumber: [{
          required: true,
          message: '请输入手机',
          trigger: 'blur'
        }],
        birth: [{required: true, message: '请选择生日', trigger: 'change'}],
      },
      sexOptions: [{
        "label": "男",
        "value": 0
      }, {
        "label": "女",
        "value": 1
      }, {
        "label": "保密",
        "value": 2
      }],
    }
  },
  computed: {},
  watch: {
    // 监听 addOrUpdateVisible 改变
    addOrUpdateVisible() {
      this.showDialog = this.addOrUpdateVisible
    },
    userInfo(userInfo){

    }
  },
  created() {

  },
  mounted() {
  },
  methods: {
    onOpen() {
      /*获取部门信息*/
     findDeptAndCount().then((res) => {
       this.departments=res.data.deptList
     })
      if(this.userInfo.id!==undefined){
        this.formData.avatar=this.userInfo.avatar
        this.formData.birth=this.userInfo.birth
        this.formData.departmentId=this.userInfo.departmentId
        this.formData.email=this.userInfo.email
        this.formData.id=this.userInfo.id
        this.formData.nickname=this.userInfo.nickname
        this.formData.password=this.userInfo.password
        this.formData.phoneNumber=this.userInfo.phoneNumber
        this.formData.username=this.userInfo.username
        this.formData.sex=this.userInfo.sex
      }
      else {
        this.formData={
          username: undefined,
              avatar:'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
              departmentId: undefined,
              nickname: undefined,
              sex: undefined,
              password: undefined,
              email: undefined,
              phoneNumber: undefined,
              birth: undefined,
        }
      }

      if (this.formData.avatar===undefined){
        this.formData.avatar='https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191'
      }
    },
    close() {
      this.$emit('showAddOrUpdate', 'false')
    },
    /**
     * 提交表单
     */
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.formData.id===undefined){
         // console.log("添加")
          addUser(this.formData).then((res) => {
            if (res.success){
              this.$message({
                type: 'success',
                message: res.message
              })
              this.$emit('updateUserList')
            }else {
              this.$message({
                type: 'info',
                message: res.message
              });
            }
          },(err) => {
            this.$message.error("添加失败")
          })
        }else {
         // console.log("修改")
          editUser(this.formData).then((res) => {
            if (res.success){
              this.$message({
                type: 'success',
                message: res.message
              })
              this.$emit('updateUserList')
            }else {
              this.$message({
                type: 'info',
                message: res.message
              });
            }
          },(err) => {
            this.$message.error("修改失败")
          })
        }

        this.close()
      })
    },
    // 上传成功后的回调函数
    cropSuccess(data) {
      const oldFileName = this.formData.avatar;
      this.imagecropperShow = false
      this.formData.avatar = data.url;
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1
      //删除数据库原有的文件
      deleteFile(oldFileName)
    },

    // 关闭上传组件
    closeImage() {
      this.imagecropperShow = false
      // 上传失败后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1
    }
  }

}

</script>
<style>
</style>
